# coding=utf-8

# 微信公众号相关方法
import json

from django.http import HttpResponse
from django.shortcuts import redirect
from wechatpy import WeChatOAuth
from worldcup.apps.userModel.models import User, UserUnion
import logging
import logging.handlers
import sys

logger = logging.getLogger('django')
reload(sys)
sys.setdefaultencoding('utf8')

APP_ID = "wx3d857b42797b5eb4"

APP_SECRET = "90364d4eec9ab9246ff64d32207b227a"

CALLBACK_URL = "https://worldcup.dmpb.com.cn/auth/callback/"


# weChatAuth = WeChatOAuth(APP_ID, APP_SECRET, CALLBACK_URL, 'snsapi_userinfo')

def auth(request):
	path = request.GET.get("path")
	if path is None:
		path = "https://worldcup.dmpb.com.cn/front/dist/index.html"
	entrance_type = request.GET.get("joboEntrance")  # 1为小程序
	if entrance_type is None:
		entrance_type = "0"
	if "?" in path:
		path = path + "&joboEntrance=" + str(entrance_type)
	else:
		path = path + "?joboEntrance=" + str(entrance_type)
	try:
		openId = request.COOKIES['openId']
	except KeyError:
		weChatAuth = WeChatOAuth(APP_ID, APP_SECRET, CALLBACK_URL, 'snsapi_userinfo', path)
		url = weChatAuth.authorize_url
		return redirect(url)
	if (openId is not None):
		logger.info("cookies中存在openId，不需要授权")
		return redirect('https://worldcup.dmpb.com.cn/front/dist/index.html')
	else:
		weChatAuth = WeChatOAuth(APP_ID, APP_SECRET, CALLBACK_URL, 'snsapi_userinfo', path)
		url = weChatAuth.authorize_url
		return redirect(url)


def auth_callback(request):
	# code可获取access_token\openId，每次用户授权带上的code将不一样，code只能使用一次，5分钟未被使用自动过期
	code = request.GET.get("code")
	path = request.GET.get("state")
	logger.info("path = " + path)
	weChatAuth = WeChatOAuth(APP_ID, APP_SECRET, CALLBACK_URL, 'snsapi_userinfo', path)
	if code:
		# 获取access_token
		token_data = weChatAuth.fetch_access_token(code)
		# 获取用户信息
		user_info = weChatAuth.get_user_info(access_token=token_data['access_token'], openid=token_data['openid'])
		logger.info(user_info)
		# 判断表中是有有此用户，根据openId判断
		try:
			user = User.objects.filter(openid=user_info["openid"]).get()
		except User.DoesNotExist:
			user = User(
				openid=user_info["openid"],
				wxname=user_info["nickname"],
				gender=user_info["sex"],
				province=user_info["province"],
				city=user_info["city"],
				country=user_info["country"],
				imgurl=user_info["headimgurl"]
			)
			user.save()
		else:
			logger.info("用户已存在 更新，微信名为：" + user_info["nickname"])
			user.wxname = user_info["nickname"]
			user.gender = user_info["sex"]
			user.province = user_info["province"]
			user.city = user_info["city"]
			user.country = user_info["country"]
			user.imgurl = user_info["headimgurl"]
			user.save()

		# 更新userunion表
		user_unions = UserUnion.objects.filter(unionid=user_info["unionid"]).all()
		if len(user_unions) == 0:
			# insert
			user_union = UserUnion(openid=user_info["openid"], unionid=user_info["unionid"])
			user_union.save()
		else:
			# 更新
			user_union = user_unions[0]
			user_union.openid = user_info["openid"]
			user_union.save()

		# 授权成功 返回页面
		request.session["wxname"] = user.wxname
		request.session["openid"] = user.openid
		request.session["gender"] = user.gender
		request.session["province"] = user.province
		request.session["city"] = user.city
		request.session["country"] = user.country
		request.session["imgurl"] = user.imgurl

		# response.set_cookie("username", username, 3600)
		response = redirect(path)
		response["openId"] = user.openid
		# response = HttpResponse(json.dumps({"ret": 0}), content_type="application/json")
		response.set_cookie('openId', user.openid, max_age=7 * 24 * 60 * 60)
		return response
	else:
		# 用户禁止授权？
		pass
